package com.zuipin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.product.ProductExtInfo;
import com.zuipin.entity.product.TagInfo;
import com.zuipin.entity.product.TagProduct;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.TagInfoMapper;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.service.ITagInfoService;
import com.zuipin.service.ITagProductService;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;

import net.sf.json.JSONObject;

/**
 * 商品标签信息业务类实现
 *
 * @ClassName TagInfoServiceImpl
 * @author wangcongyi
 * @date 2017年7月5日 下午6:40:16
 */
@Service
public class TagInfoServiceImpl implements ITagInfoService {
	
	@Resource
	private TagInfoMapper			tagInfoMapper;
	@Resource
	private IProductExtInfoService	productExtInfoService;
	@Resource
	private ITagProductService		tagProductService;
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return tagInfoMapper.deleteByPrimaryKey(id);
	}
	
	@Override
	public int insert(TagInfo record) {
		// TODO Auto-generated method stub
		return tagInfoMapper.insert(record);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean insertTagInfo(TagInfo record) {
		// TODO Auto-generated method stub
		// 获取当前时间
		String currentTime = DateUtils.getCurrentDateTime();
		record.setCreateTime(currentTime);
		record.setState(TagInfo.NOT_ENABLED);
		tagInfoMapper.insertSelective(record);
		String proSkus = record.getProSkus();
		String[] arr = proSkus.split(",");
		List<TagProduct> tagProducts = new ArrayList<>();
		for (int i = 0; i < arr.length; i++) {
			TagProduct tagProduct = new TagProduct();
			tagProduct.setTagId(record.getId());
			tagProduct.setCreateTime(currentTime);
			tagProduct.setProSku(arr[i]);
			tagProduct.setSysId(record.getSysId());
			tagProducts.add(tagProduct);
		}
		tagProductService.insertBatch(tagProducts);
		return true;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateTagInfo(TagInfo record) throws CustomException {
		// TODO Auto-generated method stub
		String currentTime = DateUtils.getCurrentDateTime();
		// 获取修改前的标签对象
		TagInfo tagInfo = tagInfoMapper.selectByPrimaryKey(record.getId());
		if (null != tagInfo) {
			if (null != record.getProSkus()) {
				List<String> skus = tagProductService.selectSkusByTagId(record.getId());
				String proSkus = record.getProSkus();
				String[] arr = proSkus.split(",");
				if (TagInfo.ENABLED.equals(tagInfo.getState())) {
					if (null != skus && !skus.isEmpty()) {
						productExtInfoService.removeTagInfo(tagInfo.getSysId(), skus);
					}
					// 更新商品标签
					List<String> proSkuList = new ArrayList<>();
					for (int i = 0; i < arr.length; i++) {
						proSkuList.add(arr[i]);
					}
					record.setSysId(tagInfo.getSysId());
					productExtInfoService.updateTagInfoBatch(record, proSkuList);
				}
				// 删除旧的标签-商品列表
				if (null != skus && !skus.isEmpty()) {
					JSONObject params = new JSONObject();
					params.put("sysId", tagInfo.getSysId());
					params.put("delFlag", true);
					tagProductService.removeRepeat(params, skus);
				}
				// 插入新的标签-商品列表
				List<TagProduct> tagProducts = new ArrayList<>();
				for (int i = 0; i < arr.length; i++) {
					TagProduct tagProduct = new TagProduct();
					tagProduct.setTagId(tagInfo.getId());
					tagProduct.setCreateTime(currentTime);
					tagProduct.setProSku(arr[i]);
					tagProduct.setSysId(tagInfo.getSysId());
					tagProducts.add(tagProduct);
				}
				tagProductService.insertBatch(tagProducts);
			}
			record.setUpdateTime(currentTime);
			record.setProSkus(null);
			tagInfoMapper.updateByPrimaryKeySelective(record);
		} else {
			throw new CustomException(ErrorCode.NOT_FIND.getCode(), "请输入正确的商品标签信息");
		}
		return true;
	}
	
	@Override
	public TagInfo selectByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return tagInfoMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public int updateByPrimaryKey(TagInfo record) {
		// TODO Auto-generated method stub
		return tagInfoMapper.updateByPrimaryKey(record);
	}
	
	@Override
	public String getMaxNo() {
		// TODO Auto-generated method stub
		return tagInfoMapper.getMaxNo();
	}
	
	@Override
	public List<TagInfo> seachTagInfo(TagInfo tagInfo, Pagination page) {
		// TODO Auto-generated method stub
		return tagInfoMapper.seachTagInfo(tagInfo, page);
	}
	
	@Override
	public TagInfo findTagInfoById(TagInfo tagInfo) {
		// TODO Auto-generated method stub
		return tagInfoMapper.findTagInfoById(tagInfo);
	}
	
	@Override
	public TagInfo isRepeat(TagInfo tagInfo) {
		// TODO Auto-generated method stub
		return tagInfoMapper.isRepeat(tagInfo);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result modifyState(TagInfo tagInfo, Boolean flag) throws CustomException {
		Result result = new Result();
		
		StringBuilder sb = new StringBuilder();
		
		// flag false 询问时 true 覆盖
		List<String> skus = tagProductService.selectSkusByTagId(tagInfo.getId());
		
		// 启用
		if (tagInfo.getState().equals(TagInfo.ENABLED)) {
			if (!flag) {
				
				List<ProductExtInfo> proExts = productExtInfoService.isSettledTagInfo(skus, tagInfo.getId());
				String data = "";
				// 询问时
				if (null != proExts && !proExts.isEmpty()) {
					sb.append("商品[");
					
					String sp = "";
					for (ProductExtInfo productExtInfo : proExts) {
						sb.append(sp);
						sb.append(productExtInfo.getProSku());
						sp = ",";
					}
					data = sb.toString().substring(3);
					
					sb.append("]已存在启用标签！是否覆盖?");
					result.setErrorCode(ErrorCode.OBJECT_EXIST);
					result.setMessage(sb.toString());
					result.setData(data);
					return result;
				} else {
					result.setErrorCode(ErrorCode.SUCCESS);
					result.setMessage("启用成功");
					// TODO 更新标签状态
					tagInfoMapper.modifyState(tagInfo);
					
					// 重新绑定状态
					productExtInfoService.updateTagInfoBatch(tagInfo, skus);
				}
				
			} else {
				// 覆盖
				// todo 3 绑定 改变状态
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setMessage("启用成功");
				
				// 获取已存在标签的商品
				List<ProductExtInfo> proExts = productExtInfoService.isSettledTagInfo(skus, tagInfo.getId());
				List<String> list = new ArrayList<>();
				
				for (ProductExtInfo productExtInfo : proExts) {
					list.add(productExtInfo.getProSku());
				}
				
				removeRebindAndUpdateState(tagInfo, list);
			}
			return result;
		} else {
			// 禁用
			
			// 更新标签状态为禁用
			tagInfoMapper.modifyState(tagInfo);
			
			// 移除扩展表里字段tagInfo信息
			tagInfo.setId(null);
			productExtInfoService.updateTagInfoBatch(tagInfo, skus);
			
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setMessage("禁用成功");
			return result;
		}
		
	}
	
	/**
	 * 启用标签 删除重复商品 重新绑定 更新状态
	 * @param tagInfo
	 * @param skus
	 */
	private void removeRebindAndUpdateState(TagInfo tagInfo, List<String> skus) {
		// todo 移除tagProduct对应关系的数据
		JSONObject params = new JSONObject();
		params.put("tagId", tagInfo.getId());
		params.put("sysId", tagInfo.getSysId());
		params.put("delFlag", true);
		tagProductService.removeRepeat(params, skus);
		
		// TODO 重新绑定
		productExtInfoService.updateTagInfoBatch(tagInfo, skus);
		// TODO 更新标签状态
		tagInfoMapper.modifyState(tagInfo);
	}
	
	@Override
	public String findSkusByTagId(TagInfo tagInfo) {
		// TODO Auto-generated method stub
		return tagInfoMapper.findSkusByTagId(tagInfo);
	}
	
}
